package softwaretest.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import softwaretest.Domain.Device;
import softwaretest.Domain.DeviceData;
import softwaretest.Domain.Greenhouse;
import softwaretest.Domain.SensorToken;
import softwaretest.repository.DeviceRepository;
import softwaretest.repository.DeviceDataRepository;
import softwaretest.repository.GreenhouseRepository;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DeviceDataService {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private GreenhouseRepository greenhouseRepository;

    @Autowired
    private DeviceRepository deviceRepository;

    @Autowired
    private DeviceDataRepository deviceDataRepository;

    private static final String DATA_URL_TEMPLATE = "https://fbox360.com/api/v2/dmon/value/get?boxNo=%s";
@Scheduled(fixedRate = 60000)
    public void fetchDataAndStore() {
        // 获取有效的令牌
        SensorToken token = tokenService.getValidSensorToken();
        if (token == null) {
            System.err.println("Failed to obtain a valid token.");
            return;
        }

        // 获取ID为1的大棚
        Greenhouse greenhouse = greenhouseRepository.findById(1L).orElse(null);
        if (greenhouse == null) {
            System.err.println("Greenhouse not found.");
            return;
        }

        String url = String.format(DATA_URL_TEMPLATE, greenhouse.getFbox());

        List<Device> devices = deviceRepository.findAll(); // 获取所有设备
        List<String> deviceIds = devices.stream()
                .filter(device -> device.getMonitoringUrl() == null || device.getMonitoringUrl().isEmpty())
                .map(Device::getSerialNumber)
                .collect(Collectors.toList());

        if (deviceIds.isEmpty()) {
            System.err.println("No valid devices found to send requests.");
            return;
        }

        Map<String, List<String>> requestBody = new HashMap<>();
        requestBody.put("ids", deviceIds);

        // 准备请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(org.springframework.http.MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + token.getAccessToken());

        // 创建请求实体
        HttpEntity<Map<String, List<String>>> requestEntity = new HttpEntity<>(requestBody, headers);

        RestTemplate restTemplate = new RestTemplate();
        try {
            // 发送请求并获取响应
            ResponseEntity<List<Map<String, Object>>> responseEntity = restTemplate.exchange(
                    url, HttpMethod.POST, requestEntity,
                    new ParameterizedTypeReference<List<Map<String, Object>>>() {}); // 使用 ParameterizedTypeReference

            List<Map<String, Object>> dataList = responseEntity.getBody();

            // 处理响应并保存到数据库
            for (Map<String, Object> data : dataList) {
                DeviceData deviceData = new DeviceData();
                Device device = deviceRepository.findBySerialNumber((String) data.get("id"));
                if (device != null) { // 确保找到了设备
                    deviceData.setDevice(device);

                    // 安全地检查类型
                    Object value = data.get("value");
                    if (value instanceof Number) {
                        deviceData.setValue(((Number) value).doubleValue()); // 转换为 double
                    } else {
                        System.err.println("Invalid value type for device: " + data.get("id"));
                        continue; // 如果值类型无效，则跳过此条目
                    }

                    deviceData.setCreatedAt(LocalDateTime.now());
                    deviceDataRepository.save(deviceData); // 保存到数据库
                }
            }
        } catch (Exception e) {
            System.err.println("Error fetching data: " + e.getMessage());
        }
    }
}